import 'package:flutter/material.dart';

class Exhibition {
  final String id;
  final String title;
  final String description;
  final String imageUrl;
  final String location;
  final DateTime startDate;
  final DateTime endDate;
  final String category;
  final String status;
  final List<String> highlights;
  final double price;
  final String organizer;
  final List<String> imageGallery;
  final Map<String, dynamic> virtualTour;

  Exhibition({
    required this.id,
    required this.title,
    required this.description,
    required this.imageUrl,
    required this.location,
    required this.startDate,
    required this.endDate,
    required this.category,
    required this.status,
    required this.highlights,
    required this.price,
    required this.organizer,
    required this.imageGallery,
    required this.virtualTour,
  });

  Exhibition copyWith({
    String? id,
    String? title,
    String? description,
    String? imageUrl,
    String? location,
    DateTime? startDate,
    DateTime? endDate,
    String? category,
    String? status,
    List<String>? highlights,
    double? price,
    String? organizer,
    List<String>? imageGallery,
    Map<String, dynamic>? virtualTour,
  }) {
    return Exhibition(
      id: id ?? this.id,
      title: title ?? this.title,
      description: description ?? this.description,
      imageUrl: imageUrl ?? this.imageUrl,
      location: location ?? this.location,
      startDate: startDate ?? this.startDate,
      endDate: endDate ?? this.endDate,
      category: category ?? this.category,
      status: status ?? this.status,
      highlights: highlights ?? this.highlights,
      price: price ?? this.price,
      organizer: organizer ?? this.organizer,
      imageGallery: imageGallery ?? this.imageGallery,
      virtualTour: virtualTour ?? this.virtualTour,
    );
  }
}

class ExhibitionProvider extends ChangeNotifier {
  List<Exhibition> _exhibitions = [];
  List<Exhibition> _filteredExhibitions = [];
  String _selectedCategory = 'all';
  String _searchQuery = '';
  bool _isLoading = false;
  String? _error;
  
  // 用户相关数据
  List<String> _favoriteExhibitionIds = [];
  List<String> _visitedExhibitionIds = [];
  Map<String, Map<String, dynamic>> _userVisits = {};
  Map<String, DateTime> _reservations = {};

  // Getters
  List<Exhibition> get exhibitions => _exhibitions;
  List<Exhibition> get filteredExhibitions => _filteredExhibitions;
  String get selectedCategory => _selectedCategory;
  String get searchQuery => _searchQuery;
  bool get isLoading => _isLoading;
  String? get error => _error;
  List<String> get favoriteExhibitionIds => _favoriteExhibitionIds;
  List<String> get visitedExhibitionIds => _visitedExhibitionIds;
  Map<String, Map<String, dynamic>> get userVisits => _userVisits;
  Map<String, DateTime> get reservations => _reservations;

  ExhibitionProvider() {
    _loadInitialData();
  }

  void _loadInitialData() {
    _isLoading = true;
    notifyListeners();

    // 模拟加载数据
    Future.delayed(const Duration(milliseconds: 500), () {
      _exhibitions = _generateMockExhibitions();
      _filteredExhibitions = List.from(_exhibitions);
      _loadUserData();
      _isLoading = false;
      notifyListeners();
    });
  }

  List<Exhibition> _generateMockExhibitions() {
    return [
      Exhibition(
        id: '1',
        title: '中华传统书画精品展',
        description: '汇集历代书画名家作品，展现中华书画艺术的博大精深。包含唐宋元明清各朝代的经典作品，以及当代书画大师的精品力作。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20calligraphy%20and%20painting%20exhibition&image_size=landscape_4_3',
        location: '市博物馆一楼展厅',
        startDate: DateTime.now().subtract(const Duration(days: 10)),
        endDate: DateTime.now().add(const Duration(days: 30)),
        category: 'art',
        status: 'ongoing',
        highlights: ['王羲之真迹', '齐白石画作', '现代书法精品'],
        price: 50.0,
        organizer: '市博物馆',
        imageGallery: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20chinese%20calligraphy%20scroll&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20landscape%20painting&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20ink%20painting%20flowers&image_size=square',
        ],
        virtualTour: {
          'available': true,
          'url': 'https://virtual-tour.example.com/calligraphy',
          'duration': 45,
        },
      ),
      Exhibition(
        id: '2',
        title: '古代陶瓷艺术展',
        description: '展示中国古代陶瓷工艺的发展历程，从原始陶器到精美瓷器，见证中华陶瓷文化的辉煌成就。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20chinese%20ceramics%20and%20pottery%20exhibition&image_size=landscape_4_3',
        location: '文化中心二楼',
        startDate: DateTime.now().add(const Duration(days: 5)),
        endDate: DateTime.now().add(const Duration(days: 45)),
        category: 'craft',
        status: 'upcoming',
        highlights: ['唐三彩', '宋代官窑', '明清青花瓷'],
        price: 40.0,
        organizer: '文化遗产保护中心',
        imageGallery: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=tang%20dynasty%20tri-color%20ceramics&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=song%20dynasty%20celadon%20pottery&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ming%20blue%20and%20white%20porcelain&image_size=square',
        ],
        virtualTour: {
          'available': true,
          'url': 'https://virtual-tour.example.com/ceramics',
          'duration': 35,
        },
      ),
      Exhibition(
        id: '3',
        title: '民族服饰文化展',
        description: '展现56个民族的传统服饰文化，了解各民族独特的服饰特色和文化内涵。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20ethnic%20clothing%20exhibition%20china&image_size=landscape_4_3',
        location: '民族文化馆',
        startDate: DateTime.now().subtract(const Duration(days: 5)),
        endDate: DateTime.now().add(const Duration(days: 25)),
        category: 'culture',
        status: 'ongoing',
        highlights: ['汉族传统服饰', '少数民族盛装', '节庆礼服'],
        price: 30.0,
        organizer: '民族文化研究院',
        imageGallery: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=han%20dynasty%20traditional%20clothing&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=tibetan%20traditional%20costume&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=mongolian%20traditional%20dress&image_size=square',
        ],
        virtualTour: {
          'available': false,
          'url': '',
          'duration': 0,
        },
      ),
      Exhibition(
        id: '4',
        title: '古代乐器文物展',
        description: '收藏展示各朝代的传统乐器文物，聆听历史的音韵，感受古代音乐文化的魅力。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20chinese%20musical%20instruments%20exhibition&image_size=landscape_4_3',
        location: '音乐博物馆',
        startDate: DateTime.now().add(const Duration(days: 15)),
        endDate: DateTime.now().add(const Duration(days: 60)),
        category: 'music',
        status: 'upcoming',
        highlights: ['编钟', '古琴', '箫笛'],
        price: 35.0,
        organizer: '音乐文化协会',
        imageGallery: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20chinese%20bronze%20bells%20bianzhong&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20guqin%20instrument&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=ancient%20chinese%20flute%20xiao&image_size=square',
        ],
        virtualTour: {
          'available': true,
          'url': 'https://virtual-tour.example.com/instruments',
          'duration': 40,
        },
      ),
      Exhibition(
        id: '5',
        title: '传统建筑艺术展',
        description: '通过模型、图片和多媒体展示中国传统建筑的精湛工艺和独特美学。',
        imageUrl: 'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20architecture%20exhibition%20models&image_size=landscape_4_3',
        location: '建筑艺术馆',
        startDate: DateTime.now().subtract(const Duration(days: 20)),
        endDate: DateTime.now().add(const Duration(days: 10)),
        category: 'architecture',
        status: 'ongoing',
        highlights: ['故宫建筑', '园林艺术', '民居特色'],
        price: 45.0,
        organizer: '建筑文化研究所',
        imageGallery: [
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=forbidden%20city%20architecture%20model&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=chinese%20garden%20architecture&image_size=square',
          'https://trae-api-us.mchost.guru/api/ide/v1/text_to_image?prompt=traditional%20chinese%20courtyard%20house&image_size=square',
        ],
        virtualTour: {
          'available': true,
          'url': 'https://virtual-tour.example.com/architecture',
          'duration': 50,
        },
      ),
    ];
  }

  void _loadUserData() {
    // 模拟加载用户数据
    _favoriteExhibitionIds = ['1', '3'];
    _visitedExhibitionIds = ['5'];
    _userVisits = {
      '5': {
        'visitDate': DateTime.now().subtract(const Duration(days: 3)),
        'rating': 5,
        'review': '非常精彩的展览，学到了很多！',
        'duration': 120, // 分钟
      },
    };
    _reservations = {
      '1': DateTime.now().add(const Duration(days: 2)),
    };
  }

  // 搜索和筛选
  void setSearchQuery(String query) {
    _searchQuery = query;
    _applyFilters();
  }

  void setCategory(String category) {
    _selectedCategory = category;
    _applyFilters();
  }

  void _applyFilters() {
    _filteredExhibitions = _exhibitions.where((exhibition) {
      final matchesCategory = _selectedCategory == 'all' || exhibition.category == _selectedCategory;
      final matchesSearch = _searchQuery.isEmpty ||
          exhibition.title.toLowerCase().contains(_searchQuery.toLowerCase()) ||
          exhibition.description.toLowerCase().contains(_searchQuery.toLowerCase());
      return matchesCategory && matchesSearch;
    }).toList();
    notifyListeners();
  }

  // 展览操作
  Future<bool> makeReservation(String exhibitionId, DateTime visitDate, Map<String, dynamic> visitorInfo) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      _reservations[exhibitionId] = visitDate;
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '预约失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> cancelReservation(String exhibitionId) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      _reservations.remove(exhibitionId);
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '取消预约失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  Future<bool> recordVisit(String exhibitionId, Map<String, dynamic> visitData) async {
    try {
      _isLoading = true;
      notifyListeners();

      // 模拟网络请求
      await Future.delayed(const Duration(seconds: 1));

      if (!_visitedExhibitionIds.contains(exhibitionId)) {
        _visitedExhibitionIds.add(exhibitionId);
      }
      
      _userVisits[exhibitionId] = {
        'visitDate': DateTime.now(),
        ...visitData,
      };
      
      _isLoading = false;
      notifyListeners();
      return true;
    } catch (e) {
      _error = '记录参观失败: $e';
      _isLoading = false;
      notifyListeners();
      return false;
    }
  }

  void toggleFavorite(String exhibitionId) {
    if (_favoriteExhibitionIds.contains(exhibitionId)) {
      _favoriteExhibitionIds.remove(exhibitionId);
    } else {
      _favoriteExhibitionIds.add(exhibitionId);
    }
    notifyListeners();
  }

  bool isFavorite(String exhibitionId) {
    return _favoriteExhibitionIds.contains(exhibitionId);
  }

  bool hasReservation(String exhibitionId) {
    return _reservations.containsKey(exhibitionId);
  }

  bool hasVisited(String exhibitionId) {
    return _visitedExhibitionIds.contains(exhibitionId);
  }

  DateTime? getReservationDate(String exhibitionId) {
    return _reservations[exhibitionId];
  }

  Map<String, dynamic>? getVisitData(String exhibitionId) {
    return _userVisits[exhibitionId];
  }

  // 获取展览详情
  Exhibition? getExhibitionById(String id) {
    try {
      return _exhibitions.firstWhere((exhibition) => exhibition.id == id);
    } catch (e) {
      return null;
    }
  }

  // 获取推荐展览
  List<Exhibition> getRecommendedExhibitions({int limit = 5}) {
    final recommended = <Exhibition>[];
    
    // 优先推荐用户收藏类别的展览
    final favoriteCategories = _favoriteExhibitionIds
        .map((id) => getExhibitionById(id)?.category)
        .where((category) => category != null)
        .toSet();
    
    for (final exhibition in _exhibitions) {
      if (favoriteCategories.contains(exhibition.category) && 
          !_visitedExhibitionIds.contains(exhibition.id)) {
        recommended.add(exhibition);
      }
    }
    
    // 如果推荐数量不够，添加其他展览
    if (recommended.length < limit) {
      for (final exhibition in _exhibitions) {
        if (!recommended.contains(exhibition) && 
            !_visitedExhibitionIds.contains(exhibition.id)) {
          recommended.add(exhibition);
        }
        if (recommended.length >= limit) break;
      }
    }
    
    return recommended.take(limit).toList();
  }

  // 获取正在进行的展览
  List<Exhibition> getOngoingExhibitions() {
    return _exhibitions.where((exhibition) => exhibition.status == 'ongoing').toList();
  }

  // 获取即将开始的展览
  List<Exhibition> getUpcomingExhibitions() {
    return _exhibitions.where((exhibition) => exhibition.status == 'upcoming').toList();
  }

  // 获取用户统计数据
  Map<String, dynamic> getUserStats() {
    final totalVisitTime = _userVisits.values
        .map((visit) => visit['duration'] as int? ?? 0)
        .fold(0, (sum, duration) => sum + duration);
    
    return {
      'totalExhibitions': _visitedExhibitionIds.length,
      'favoriteExhibitions': _favoriteExhibitionIds.length,
      'totalVisitTime': totalVisitTime, // 分钟
      'reservations': _reservations.length,
      'averageRating': _calculateAverageRating(),
    };
  }

  double _calculateAverageRating() {
    final ratings = _userVisits.values
        .map((visit) => visit['rating'] as int?)
        .where((rating) => rating != null)
        .cast<int>();
    
    if (ratings.isEmpty) return 0.0;
    
    return ratings.reduce((a, b) => a + b) / ratings.length;
  }

  // 获取展览分类
  List<String> getCategories() {
    final categories = _exhibitions.map((e) => e.category).toSet().toList();
    categories.sort();
    return ['all', ...categories];
  }

  // 刷新数据
  Future<void> refresh() async {
    _error = null;
    _loadInitialData();
  }

  // 清除错误
  void clearError() {
    _error = null;
    notifyListeners();
  }
}